package com.lagou.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private Object para;

    private ServerInfo serverInfo;


    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {

        result = msg.toString();
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() throws InterruptedException {

        //打印当前调用的是哪个服务器server，验证负载均衡
        System.out.println("调用服务器server：ip=" + serverInfo.getIp()
                + ",port=" + serverInfo.getPort() + ",上次调用所花费时间=" + serverInfo.getSpendTime()+"ms");

        //每次客户端调用时，设置对应的服务器最后一次调用的系统时间
        serverInfo.setLastCallTime(System.currentTimeMillis());
        long startTime = System.nanoTime();

        context.writeAndFlush(para);
        wait(2000);

        //计算调用server所花费的时间，设置到对应的server的响应时间
        long endTime = System.nanoTime();
        long spendTime = (endTime - startTime) / 1000L;
        serverInfo.setSpendTime(spendTime);

        return result;
    }

    /*
     设置参数
     */
    void setPara(Object para) {
        this.para = para;
    }

    public ServerInfo getServerInfo() {
        return serverInfo;
    }

    public void setServerInfo(ServerInfo serverInfo) {
        this.serverInfo = serverInfo;
    }
}
